package com.qst.order.service.Impl;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.qst.order.service.OSSService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OSSServiceImpl implements OSSService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Override
    public Map<String, String> getUploadCredentials(String dirType) {
        // 根据不同的文件类型返回不同的目录
        String directory = "order-upload/";
        switch (dirType) {
            case "avatar":
                directory+="user-avatar/";
                break;
            case "image":
                directory+= "product-image/";
                break;
            default:
                throw new IllegalArgumentException("不支持的文件类型");
        }
        Map<String, String> credentials = new HashMap<>();
        credentials.put("endpoint", endpoint);
        credentials.put("accessKeyId", accessKeyId);
        credentials.put("accessKeySecret", accessKeySecret);
        credentials.put("bucketName", bucketName);
        credentials.put("dir", directory);
        return credentials;
    }

    @Override
    public String uploadFile(MultipartFile file, String dirType) throws IOException {
        // 获取对应类型的上传目录
        String directory = getUploadCredentials(dirType).get("dir");

        System.out.println("上传中.......");
        // 或者直接在这里处理目录逻辑（避免重复获取凭证）
        // 初始化OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 生成唯一文件名
            String fileName = directory + UUID.randomUUID() +
                    getFileExtension(file.getOriginalFilename());

            // 上传文件
            ossClient.putObject(bucketName, fileName, file.getInputStream());

            // 生成访问URL
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        } finally {
            ossClient.shutdown();
        }
    }


    private String getFileExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return ".dat"; // 默认扩展名
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 批量删除文件
     * @param fileNames 要删除的文件名列表（包含完整路径，如"music-uploads/music-mp3/xxx.mp3"）
     * @return 删除成功的文件数
     */
    @Override
    public int deleteFiles(List<String> fileNames) {
        if (fileNames == null || fileNames.isEmpty()) {
            return 0;
        }
        // 初始化OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建删除请求
            DeleteObjectsRequest deleteRequest = new DeleteObjectsRequest(bucketName);
            deleteRequest.setKeys(fileNames);

            // 执行删除
            DeleteObjectsResult deleteResult = ossClient.deleteObjects(deleteRequest);

            // 返回成功删除的文件数量
            return deleteResult.getDeletedObjects().size();
        } catch (Exception e) {
            // 处理异常，如打印日志
          throw new RuntimeException("删除文件失败: " + e.getMessage());
        } finally {
            // 关闭客户端
            ossClient.shutdown();
        }
    }
}



